///<reference path="./jquery-1.5.1-vsdoc.js"/>
///<reference path="http://api.map.baidu.com/api?v=1.5&ak=6qIIKuf2zoHcwRhoKt9GWakd"/>
$.Map = {
    infowindow: null,
    map: null,
    itemnames:null
}
$.GlobalVar ={
    cityitemid: 0,
    item: 0,
    allsite: null,
    initsite :null
}
$.initliaze = function (id, level, lat, lng, heightctrl, sid ,curDate,minPhotoTime,maxPhotoTime) {
    var sitename = new Object();
    var markers = new Array();
    var MinPhotoTime = minPhotoTime;
    var MaxPhotoTime = maxPhotoTime;
    $(function () {
        var fun = function (dy) {
            var d = function () {
                if (dy == 1 && (new Date()).setDate((new Date()).getDate() - 2) < curDate) {
                    return;
                } else if (dy == -1 && (new Date()).setDate((new Date()).getDate() - 15) > curDate) {
                    return;
                }
                curDate.setDate(curDate.getDate() + dy);
                $.ajax({
                    url: "/Home/GetAqi",
                    type: "post",
                    dataType: "json",
                    data: { dt: curDate.getFullYear() * 10000 + (curDate.getMonth() + 1) * 100 + curDate.getDate() },
                    error: function (a, b, c) {
                    },
                    success: function (dict) {
                        if (dict.AQI == 0)
                        {
                            dict.AQI = "--";
                        }
                    $(".dayDate").html(curDate.getFullYear() + "年" + (curDate.getMonth() + 1) + "月" + curDate.getDate() + "日");
                        //$(".dayDate").html(dict.time.toString("yyyy年MM月dd日"));
                        $(".dayValue").html(dict.AQI);
                        $(".dayLevel").html(dict.Level);
                        $(".dayFirst").html(dict.FirstPopu);
                        $(".dayDesc").html(dict.Description);
                        $(".dayColor").attr("style", function ()
                        {
                            if (dict.AQI == "--") { return "background-color:#808080"; }
                            else {
                                return "background-color:#" + dict.color.Name.substring(2);
                            }
                        });
                    }
                });
            };
            return d;
        };
        $("#prevDay").click(fun(-1));
        $("#nextDay").click(fun(1));
       
    });
    $(function () {
        var photofun = function (step) {
             var d = function () {
                var cursrc = $(".photo").attr("src");
                var cur = cursrc.substring(8, 18);
                if (step == -1 && cur <= MinPhotoTime || step == 1 && cur >= MaxPhotoTime) return;
                $.ajax({
                    url: "/Home/GetPhoto",
                    type: "post",
                    dataType: "json",
                    data: { v: cursrc, s: step },
                    success: function (p) {
                        if (p.url.substring(0, 10) < MinPhotoTime && p.url.substring(0, 10) > MaxPhotoTime) return;
                        $(".photo").attr("src", "/Home/i/" + escape(p.url));
                        $(".phototime").html((p.time) + "<br/>");
                    }
                });
            };
            return d;
        };
        $(".arrow_left").click(photofun(-1));
        $(".arrow_right").click(photofun(1));
    })


    function CustomInfoWindow(center,context,length){
        this._context = context;
        this._center = center;
        this._length = length;
    }
    CustomInfoWindow.prototype = new BMap.Overlay();
    CustomInfoWindow.prototype.initialize = function (map) {
        this._map = map;
        var div = document.createElement("div");
        div.innerHTML = this._context;


        div.style.position = "absolute";        
          
        div.style.width = this._length + "px";    
        div.style.height = this._length + "px";    
      
  
        map.getPanes().markerPane.appendChild(div);   

        this._div = div;
        return div;
    }
   
    CustomInfoWindow.prototype.draw = function () {
       // 根据地理坐标转换为像素坐标，并设置给容器    
        var position = this._map.pointToOverlayPixel(this._center);    
        this._div.style.left = position.x - this._length / 2 + "px";    
        this._div.style.top = position.y - this._length / 2 + "px";    
    } 
    CustomInfoWindow.prototype.show = function () {
        if (this._div){    
            this._div.style.display = "";    
         }    
    }      

    CustomInfoWindow.prototype.hide = function () {
        if (this._div){    
            this._div.style.display = "none";    
        }    
    }
    function getXmlByItem(sname, item, managelevel, sitedata, html, sitecode) {
        xmlData = sitedata.DayDataXml;
        day7 = sitedata.WeekDataXml;
        html = html.replace(/\$site/g, sname)
                .replace(/\$stype/g, managelevel)
                .replace(/\$item/g, item == 812 ? "O<sub>3</sub> 8小时" :$.GlobalVar.itemnames["i" + item])
                .replace(/\$time/g, sitedata.DateTime)
                .replace(/\$24conc/g, sitedata.HourValue)
                .replace(/\$conc/g, sitedata.Value)
                .replace(/\$unit/g, sitedata.Unit)
                .replace(/\$iaqi/g, $.GlobalVar.allsite["i" + item]["s" + sitecode])
                .replace(/\$level/g, sitedata.AQI.LevelDescription)
                .replace(/\$desc/g, sitedata.AQI.Description)
                .replace(/\$aqi/g, sitedata.AQI.AQI.Value)
        ;
        html = html.replace(/\$disnone/g, item == 2220 || item == 2221 ? "" : "style=\"display:none;\" ");
        html = html.replace(/\$colnum/g, item == 2220 || item == 2221 ? 4 : 3);

        return html;
    }

    $(function(){
        $(".sw").mouseenter(function () {

            $(".mitem_all").css("visibility", "visible")
                .css("top", 20 + $(".sw").index(this) * 54);

            $.GlobalVar.cityitemid = $(this).attr("data-item");
        }).mouseout(function () {
            $(".mitem_all").css("visibility", "hidden");
        }).click(function () {
            switchitem(this);
            $("#city").html("").css("display", "none");
        });

        $(".mitem_all").mouseenter(function () {
            $(this).css("visibility", "visible");
        }).mouseout(function () {
            $(this).css("visibility", "hidden");
        }).click(function () {
            $.ajax({
                url: "/Home/GetDataBySiteItem"
                , type: "post"
                , dataType: "json"
                , data: { site: "0", item: $.GlobalVar.cityitemid }
                , success: function (sitedata) {


                    if ($.GlobalVar.cityitemid != 0) {
                        var html = document.getElementById("box").innerHTML;
                        $("#city").html(getXmlByItem("全市", $.GlobalVar.cityitemid, "国控点", sitedata, html)).css("display", "block");
               
                    }
                    else {
                        var html = document.getElementById("box2").innerHTML;
                        $("#city").html(getXmlBySite("全市", "国控点", sitedata, html)).css("display", "block");

                    }
                    $("#city .btnclose").css("visibility", "visible");
                    $("#city .btnclose").click(function () {
                        $("#city").html("").css("display", "none");
                    });

                }//emd success
            });//end ajax
        });
    });




    function switchitem(obj) {
        var th = $(obj);
        var id = th.attr("data-item");
        var k = $(".mitem_" + $.GlobalVar.item);
        $(".mitem_" + $.GlobalVar.item).css("background", "url(../images/NJ_AQI_NAV_" + $.GlobalVar.item + ".png) no-repeat");
        $.GlobalVar.item = id;
        th.css("background", "url(../images/NJ_AQI_NAV_hov_" + id + ".png) no-repeat");

        var d = id != 0 ? $.GlobalVar.allsite["i" + id] : $.GlobalVar.initsite;

        for (var i = 0 ; i < markers.length; ++i) {
            var m = markers[i];
            var map = m.map;
            m.setIcon( new BMap.Icon(  "/Home/SiteImage?aqi=" + d["s" + m.sitecode] + (map.levelshow ? "&s=1" : ""),new BMap.Size(24, 24)));
        }
    }
    $(function () {
        var map = $.Map.map = new BMap.Map(id);
        var opts = { offset: new BMap.Size(600, 40) }
        map.centerAndZoom(new BMap.Point(lat, lng), level);
        map.addControl(new BMap.NavigationControl(opts));
        map.addControl(new BMap.OverviewMapControl());
        map.addControl(new BMap.MapTypeControl());
        var homeControl = new HomeControl(function () { map.centerAndZoom(new BMap.Point(lat, lng), level); });
        map.addControl(homeControl);

        // var fillcolor = "#e0e0e0";
        // var alpha = 0.7;
        // getBoundary(map, "安徽省", alpha, fillcolor, 0);
        // getBoundary(map, "浙江省", alpha, fillcolor, 0);
        // getBoundary(map, "常州市", alpha, fillcolor, 0);
        // getBoundary(map, "镇江市", alpha, fillcolor, 0);
        // getBoundary(map, "扬州市", alpha, fillcolor, 0);
        // getBoundary(map, "淮安市", alpha, fillcolor, 0);
        // getBoundary(map, "无锡市", alpha, fillcolor, 0);
        // getBoundary(map, "苏州市", alpha, fillcolor, 0);
        // getBoundary(map, "盐城市", alpha, fillcolor, 0);
        // getBoundary(map, "泰州市", alpha, fillcolor, 0);
        // getBoundary(map, "宿迁市", alpha, fillcolor, 0);
        // getBoundary(map, "连云港市", alpha, fillcolor, 0);
        // getBoundary(map, "山东省", alpha, fillcolor, 0);
        // getBoundary(map, "南通市", alpha, fillcolor, 0);
        // getBoundary(map, "江西省", alpha, fillcolor, 0);
        // getBoundary(map, "南京市", 0, "", 1);

        $.ajax(getData(sid, map));
    });


    function getSiteXml(m, sitedata, html) {
        return getXmlBySite(m.title, m.managelevel, sitedata, html);
    }
    function getXmlBySite(sname, level, sitedata, html) {
        xmlData = sitedata.DayXml;
        day7 = sitedata.WeekDataXml;
        html = html.replace(/\$site/g, sname)
            .replace(/\$stype/g, level)
            .replace(/\$level/g, sitedata.AQI.LevelDescription)
            .replace(/\$levdesc/g, sitedata.AQI.Description)
            .replace(/\$aqi/g, sitedata.AQI.AQI.Value)
            .replace(/\$popu/g, sitedata.Popu.Text)
            .replace(/\$time/g, sitedata.DateTime);
        return html;
    }

    function HomeControl(fun) {
        this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
        this.defaultOffset = new BMap.Size(10, 10);
        this.fun = fun;
    }
    HomeControl.prototype = new BMap.Control();
    HomeControl.prototype.initialize = function () {
        var div = document.createElement("div");
        var controlUI = document.createElement('div');
        controlUI.style.backgroundColor = 'white';
        controlUI.style.borderStyle = 'solid';
        controlUI.style.borderWidth = '2px';
        controlUI.style.cursor = 'pointer';
        controlUI.style.textAlign = 'center';
        controlUI.title = '复位';
        div.appendChild(controlUI);// Set CSS for the control interior.
        var controlText = document.createElement('div');
        controlText.style.fontFamily = 'Arial,sans-serif';
        controlText.style.fontSize = '12px';
        controlText.style.paddingLeft = '4px';
        controlText.style.paddingRight = '4px';
        controlText.innerHTML = '<strong>复位</strong>';
        controlUI.appendChild(controlText);
        controlUI.onclick = this.fun;
        return div;
    };
    function getSiteItemXml(m, sitedata, html) {
        var marker = m.marker;
        return getXmlByItem(sitename["s" + marker.sitecode], $.GlobalVar.item, m.managelevel, sitedata, html, marker.sitecode);
    }


    function onmarkerClick(data,m) {
        return function () {
            $("#city").html("").css("display", "none");
            $.ajax({
                url: "/Home/GetDataBySiteItem"
                , type: "post"
                , dataType: "json"
                , data: { site: data.Id, item: $.GlobalVar.item }
                , success: function (sitedata) {
                    var boxText = document.createElement("div");
                    boxText.className = "box if";
                    if ($.GlobalVar.item != 0) {
                        var html = document.getElementById("box").innerHTML;
                        boxText.innerHTML = getSiteItemXml(m, sitedata, html);
                    }
                    else {
                        var html = document.getElementById("box2").innerHTML;
                        boxText.innerHTML = getSiteXml(m, sitedata, html);
                    }
                    if ($.Map.infowindow != null) {
                        $.Map.map.removeOverlay($.Map.infowindow);
                    }
                    $.Map.infowindow = new CustomInfoWindow(m.marker.getPosition(), boxText.innerHTML, 100);
                    $.Map.map.addOverlay($.Map.infowindow);
                }
            });
        }
    }
    function getDataOnSuccess(map) {
        return function (data) {
            for (var i = 0 ; i < data.length; ++i) {
                var point = new BMap.Point(data[i].Lng, data[i].Lat);
                var label = new BMap.Label();
                label.setOffset(new BMap.Size(20, 0));
                label.setContent(data[i].Name);
                sitename["s" + data[i].Id] = data[i].Name;
                var marker = new BMap.Marker(point);
                marker.setIcon(new BMap.Icon("/Home/SiteImage?aqi=" + $.GlobalVar.initsite["s" + data[i].Id], new BMap.Size(24, 24)));
                marker.setLabel(label);
                map.addOverlay(marker);
                marker.addEventListener("click", onmarkerClick(data[i], { marker: marker, title: data[i].Name, managelevel: data[i].Level == 0 ? "国控点" : "郊区点" }));
                marker.sitecode = data[i].Id;
                markers.push(marker);
            }
        }
    }
    function getData(id, map) {
        return {
            url: "/Home/GetData",
            type: "post",
            dataType: "json",
            data: { id: id },
            success: getDataOnSuccess(map)
        };

    }
    function getBoundary(map, city, opacity, fillcolor, width) {
        var bdary = new BMap.Boundary();

        bdary.get(city, function (rs) {
            points = rs;
            var rslength = rs.boundaries.length;
            var top = 0;
            var bottom = 0;
            var left = 0;
            var right = 0;
            for (i = 0; i < rslength; i++) {
                var triangleCoords = [];
                var temp = rs.boundaries[i];
                var latLngs = temp.split(";");
                for (j = 1; j < latLngs.length - 1; j++) {
                    var postion = latLngs[j].indexOf(",");
                    var lat = parseFloat(latLngs[j].substr(0, postion));
                    var lng = parseFloat(latLngs[j].substr(postion + 1));
                    triangleCoords.push(new BMap.Point(lat, lng));
                    if (j == 1 && top == 0 && bottom == 0 && left == 0 && right == 0) {
                        top = bottom = lng;
                        left = right = lat;
                    }
                    else {
                        if (lng > top) {
                            top = lng;
                        }
                        if (lng < bottom) {
                            bottom = lng;
                        }
                        if (lat > right) {
                            right = lat;
                        }
                        if (lat < left) {
                            left = lat;
                        }
                    }
                }
                bermudaTriangle = new BMap.Polygon(triangleCoords);
                if (width == 0) bermudaTriangle.setStrokeColor("");
                bermudaTriangle.setStrokeOpacity(0.8);

                bermudaTriangle.setStrokeWeight(1);
                bermudaTriangle.setFillColor(fillcolor);
                bermudaTriangle.setFillOpacity(opacity);
                map.addOverlay(bermudaTriangle);

            }

        });
    }
}

$.showchart = function (obj) {


    function showflash(obj, xml, type) {
        var chartURL = '/Content/FusionChartsSWF/' + 'FCF_' + type.replace('Chart', '.swf');
        var _lib_JS_oneday = new FusionCharts(chartURL, "_lib_OBJ_oneday", "392", "151");
        _lib_JS_oneday.setDataXML(xml);
        _lib_JS_oneday.render(obj);
    }

    var o = $(obj).parent().next();
    var ishide = o.css("display") == "none"
    o.css("display", ishide ? "block" : "none");
    var chartid = $(".area2", o)[0];

    if (ishide && $("object", o).length == 0) {
        if (obj.className == "char2")
            showflash(chartid, day7, "Column2DChart");
        else
            showflash(chartid, xmlData, "MSLineChart");

    }
}
$.closeInfoWindow = function () {
    $.Map.map.removeOverlay($.Map.infowindow);
}